package cn.hpclub.server.controller.admin;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.JFinal;

import cn.hpclub.server.bean.SystemConfig;
import cn.hpclub.server.model.ActivityOrder;
import cn.hpclub.server.service.AccountService;
import cn.hpclub.server.service.ActivityOrderService;
import cn.hpclub.server.util.ExcelLargeDataUtils;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.SystemConfigUtil;

public class ActivityOrderController extends BaseAdminController<ActivityOrder>{
    private static final String STATUS            = "status";
    private static final String MESSAGE           = "message";
    private static final String URL               = "url";
    private static final String IS_EXPORT         = "isExport";
    private static final String QUERY_DATE_FORMAT = "yyyy-MM-dd";
    private static final String END_DATE          = "end_date";
    private static final String START_DATE        = "start_date";
    private static Logger       logger            = LoggerFactory.getLogger(ActivityOrderController.class);
    private static final String ORG_ID            = "org_id";
    private static final String ORDER_STATUS       = "order_status";
    private static final String PAY_STATUS        = "pay_status";

    /**
     * @Title:list
     * @Description:商品订单列表+导出 void
     */
    public void list(){
    	logger.info("list请求开始" + isExportData());
        int defaultOrgId = initOrgTree();
        ConcurrentHashMap<String, Object> searchInfo = getObjectSearchFilter();
        // 第一次进入，没有选中，则默认最高一层选中进行搜索。
        if(searchInfo.get(ORG_ID) == null){
            searchInfo.put(ORG_ID, String.valueOf(defaultOrgId));
        }

        String sqlSelect = ActivityOrderService.service.getSqlSelect();
        String sqlFilter = ActivityOrderService.service.getSqlFilter(searchInfo);
        // System.out.println("sql:" + sqlSelect + sqlFilter);
        if(isExportData()){
            export(sqlSelect, sqlFilter);
        } else{
            setAttrs(searchInfo);
            query(sqlSelect, sqlFilter);
        }
    }

    private ConcurrentHashMap<String, Object> getObjectSearchFilter(){
        ConcurrentHashMap<String, Object> searchInfo = getObjectSearchInfo();
        int adminId = InterfaceUtil.getAdminId();
        int userRoleType = AccountService.service.getUserRoleType(adminId);
        logger.debug("userRoleType=" + userRoleType);
        // if(userRoleType == Constant.ROLE_TYPE_SUPPLIER_ADMIN){
        // // 角色类型为供应商管理角色时，只能查看由该帐号创建的商品的订单
        // searchInfo.put("creator", String.valueOf(adminId));
        // } else{
        // 其他角色根据机构关系限制数据
        // searchInfo.put(ORG_ID, String.valueOf(InterfaceUtil.getOrgId()));
        // }
        setQueryTime(searchInfo);
        setDefaultCondition(searchInfo);
        return searchInfo;
    }

    /**
     * @Title: getSearchFilter
     * @Description:获取查询条件
     * @return ConcurrentHashMap<String,String>
     */
    // private ConcurrentHashMap<String, String> getSearchFilter(){
    // ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
    // int adminId = InterfaceUtil.getAdminId();
    // int userRoleType = AccountService.service.getUserRoleType(adminId);
    // logger.debug("userRoleType=" + userRoleType);
    // // if(userRoleType == Constant.ROLE_TYPE_SUPPLIER_ADMIN){
    // // // 角色类型为供应商管理角色时，只能查看由该帐号创建的商品的订单
    // // searchInfo.put("creator", String.valueOf(adminId));
    // // } else{
    // // 其他角色根据机构关系限制数据
    // searchInfo.put(ORG_ID, String.valueOf(InterfaceUtil.getOrgId()));
    // // }
    // setQueryTime(searchInfo);
    // setDefaultCondition(searchInfo);
    // return searchInfo;
    // }

    /**
     * @Title: setQueryTime
     * @Description:设置查询时间
     * @param searchInfo:查询参数列表
     */
    private void setQueryTime(ConcurrentHashMap<String, Object> searchInfo){
        if(searchInfo.get(START_DATE) == null){
            SimpleDateFormat sdf = new SimpleDateFormat(QUERY_DATE_FORMAT);
            String startDate = sdf.format(new Date());
            searchInfo.put(START_DATE, startDate);
        }
        if(searchInfo.get(END_DATE) == null){
            SimpleDateFormat sdf = new SimpleDateFormat(QUERY_DATE_FORMAT);
            String startDate = sdf.format(new Date());
            searchInfo.put(END_DATE, startDate);
        }
    }

    private void setDefaultCondition(ConcurrentHashMap<String, Object> searchInfo){
//        if(searchInfo.get(PAY_STATUS) == null){
//            JSONArray defaultValue = new JSONArray();
//            defaultValue.add("1");
//            searchInfo.put(PAY_STATUS, defaultValue);
//        }
        if(searchInfo.get(ORDER_STATUS) == null){
            searchInfo.put(ORDER_STATUS, "1");
        }
    }

    /**
     * @Title: isExportData
     * @Description:是否输出数据
     * @param isExport:
     * @return boolean
     */
    private boolean isExportData(){
        logger.debug("isExport=" + getPara(IS_EXPORT));
        return "1".equals(getPara(IS_EXPORT));
    }

    /**
     * @Title: query
     * @Description:订单查询
     * @param sqlSelect:SQL查询列表
     * @param sqlFilter:SQL查询条件语句
     */
    private void query(String sqlSelect, String sqlFilter){
        findByPageForSearch(sqlSelect, sqlFilter);
        render("/admin/activity_order_list.tpl");
    }

    /**
     * @Title: export
     * @Description:数据导出
     * @param sqlSelect:SQL查询列表
     * @param sqlFilter:SQL查询条件语句
     */
    private void export(String select, String sqlExceptSelect){
        final String[] headers = new String[] { "DZG订单编号", "移动订单编号", "用户手机号", "订单金额(元)",
                "办理人姓名", "办理人手机号 ", "办理人工号", "活动代码", "活动名称", "地市", "区县", "网点编码", "网点名称", "网点类型", "创建时间", "办理结果" };
        final String[] columns = new String[] { "order_id", "cmcc_id", "user_mobile", "order_amount",
                "staff_name", "staff_phone", "emp_code", "tariff_code", "package_name", "city", "area",
                "NumCode", "DisplayName", "sitetype", "created_datetime", "order_status" };
        String fileName = generateFileName();
        String filePath = getFilePath(fileName);
        JSONObject jo = null;
        try{
            String sql = select + sqlExceptSelect;
            String url = ExcelLargeDataUtils.exportData(headers, columns, sql, fileName, filePath);
            jo = createDownloadSuccessJSONObject(url);
        }
        catch(IOException e){
            e.printStackTrace();
            jo = createDownloadErrorJSONObject(e);
        }
        renderJson(jo.toJSONString());
    }

    /**
     * @Title: createDownloadErrorJSONObject
     * @Description:创建导出失败JSON对象
     * @param e:异常对象
     * @return JSONObject
     */
    private JSONObject createDownloadErrorJSONObject(IOException e){
        JSONObject jo = new JSONObject();
        jo.put(STATUS, 0);
        jo.put(MESSAGE, "导出失败：" + e.getMessage());
        return jo;
    }

    /**
     * @Title: createDownloadSuccessJSONObject
     * @Description:创建导出成功SON对象
     * @param exportFileUrl:导出文件URL，供浏览器下载
     * @return JSONObject
     */
    private JSONObject createDownloadSuccessJSONObject(String exportFileUrl){
        JSONObject jo = new JSONObject();
        jo.put(STATUS, 1);
        jo.put(MESSAGE, "导出成功，点击下载");
        jo.put(URL, exportFileUrl);
        renderJson(jo.toJSONString());
        return jo;
    }

    /**
     * @Title: generateFileName
     * @Description:获取文件名，根据日期创建导出文件名
     * @return String:文件名
     */
    private String generateFileName(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HHmmssSSS");
        String curTime = sdf.format(date);
        String fileName = "营销活动订单" + curTime + ".xlsx";
        return fileName;
    }

    /**
     * @Title: getFilePath
     * @Description:获取保存文件路径
     * @param name:文件名
     * @return String
     */
    private String getFilePath(String fileName){
        String filePath = JFinal.me().getServletContext().getRealPath(SystemConfig.UPLOAD_FILE_DIR + fileName);
        String fileDir = SystemConfigUtil.getSystemConfig().getUploadDir();
        if(!StringUtils.isEmpty(fileDir)){
            filePath = String.format("%s/file/%s", fileDir, fileName);
        }
        logger.debug("filePath = " + fileDir);
        return filePath;
    }
}
